package org.lb.MarketingSystem.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class FileController {
	
	@RequestMapping(value="/load")
	public String load(){
		return "load";
	}
	
	@RequestMapping(value="/upload")
	public String upload(MultipartFile imgFile,HttpSession session){
		InputStream inputStream=null;
		FileOutputStream fileOutputStream=null;
		try {
			//获取文件上传流
			inputStream=imgFile.getInputStream();
			//获取文件上传名
			String originalFilename = imgFile.getOriginalFilename();
			//获取上传文件后缀名
			String extension = FilenameUtils.getExtension(originalFilename);
			//随机产生文件新名字
			UUID fileUuid = UUID.randomUUID();
			//文件新名字
			String newFileName=fileUuid+"."+extension;
			//获取servletContext项目上下文路径
			ServletContext servletContext = session.getServletContext();
			//获取文件保存的 路径
			String realPath = servletContext.getRealPath("/upload");
			//根据路径获取File
			File realFile = new File(realPath);
			//判断文件夹是否存在，若为否，则进行创建
			if(!realFile.exists()){
				realFile.mkdirs();
			}
			//拼接上传文件夹
			realFile=new File(realFile,newFileName);
			System.out.println(realFile.getName()+"----"+realFile.getPath());
			//将文件转为输出字节流
			fileOutputStream = new FileOutputStream(realFile);
			//上传文件
			IOUtils.copy(inputStream, fileOutputStream);
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if(inputStream!=null){
				try {
					//关闭输入流
					inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(fileOutputStream!=null){
				try {
					//关闭输出流
					fileOutputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return "";
	}
}
